package com.cictec.middleware.gps.engine.position.handler.shiftAndTrip;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cictec.middleware.commons.utils.Constants;
import com.cictec.middleware.commons.utils.DateUtils;
import com.cictec.middleware.commons.utils.PMSUtils;
import com.cictec.middleware.commons.utils.log.MultiLog;
import com.cictec.middleware.core.entity.DeparterSchedule;
import com.cictec.middleware.feign.gps.caculate.MiddlewareGpsCaculateService;
import com.cictec.middleware.gps.engine.BusInstance;
import com.cictec.middleware.gps.engine.TimingPoint;
import com.cictec.middleware.gps.engine.caculate.entity.BusTrip;
import com.cictec.middleware.gps.engine.exception.BusPositionHandlerException;
import com.cictec.middleware.gps.engine.position.handler.BusPositionShiftAndTripHandler;
import com.cictec.middleware.gps.engine.utils.MultiLogUtil;
import com.cictec.middleware.gps.service.BusLineService;
import com.cictec.middleware.gps.service.ScheduleService;

/**
 * 没有上下行时候班次趟次信息处理
 * @author ql
 */
@Service
public class LineTypeExistShitTripHandler {

	private Logger logger = LoggerFactory.getLogger(BusPositionShiftAndTripHandler.class);
	
	@Autowired
	private ScheduleService scheduleService;
	@Autowired
	private BusLineService busLineService;
	@Autowired
	private MiddlewareGpsCaculateService middlewareGpsCaculateService;
	@Autowired
	private RealTripCaculateHandler realTripCaculateHandler;
	
	public void onHandler(BusInstance busInstance) throws BusPositionHandlerException {
		
		// 【班次、趟次信息】
		calculateShiftAndTrip(busInstance);
	}
	
	private void calculateShiftAndTrip(BusInstance busInstance){
		if(busInstance.isEnterOut()){
			System.out.println("ok");
		}
		if (!isTripOver(busInstance)) {
			// 当前趟次没有结束 趟次信息处理
			setCurrentTripByTripNotOver(busInstance);
		}else{
			/*
			 * 1、计算上一趟趟次信息
			 * 2、刷新当前趟次信息
			 */
			busInstance.setCurrentTripStartPoint(null);
			if(!busInstance.isBusMileageCaculate()){
				caculatePreTrip(busInstance);
				setCurrentTripByTripOver(busInstance);
			}
		}
		
		setNextDepartureSchedule(busInstance);
	}
	
	/**
	 * 判定当前趟次是否结束
	 * @return
	 */
	private boolean isTripOver(BusInstance busInstance){
		/*
		 * 双向发车，可以按照上下行切换判定
		 * 单向发车，可以按照切换上下行到上行判定
		 * 环线，按照站序判定
		 */
		Integer lineBfType = busLineService.getLineBfType(busInstance.getLineUuid()); // 发车类型（0单向 ，1双向，2环线）

		TimingPoint preTimgPoint = busInstance.getTimingPoint(-1);
		if(preTimgPoint == null){
			return false;
		}
		String preLineType = preTimgPoint.getLineType();
		String preTripNo = preTimgPoint.getCurrentTrip();
		
		String lineType = busInstance.getLineType();
		String lineUuid = busInstance.getLineUuid();
		
		boolean flag = false;
		if(0 == lineBfType){
			// 单向
			if(!preLineType.equals(lineType)
					&& Constants.VAL_LINE_UP.equals(lineType)
					){
				flag = true;
			}
			
		}else if(1 == lineBfType){
			// 双向
			if(!preLineType.equals("0") && !preLineType.equals(lineType)){
				flag = true;
			}
			
		}else if(2 == lineBfType){
			// 环线
			if(busInstance.isEnterOut()){
				TimingPoint currentStation = busInstance.getCurrentStation();
				if(currentStation != null){
					
					String lastLineUuid = currentStation.getLineUuid();
					String lastLineType = currentStation.getStationLineTypeOrg();
					String lastStationSeq = currentStation.getStationLineSeqOrg();
					
					String currentStationSeq = busInstance.getStationLineSeqOrg();
					
					if(Integer.parseInt(lastStationSeq) > Integer.parseInt(currentStationSeq)){
						flag = true;
					}
				}
			}
		}
		return flag;
	}
	
	private void setCurrentTripByTripNotOver(BusInstance busInstance) {
		if (busInstance.isInStandBy()) {
			setCurrentTripByStandby(busInstance);
		} else if (busInstance.isEnterOut()) {
			if (busInstance.getCurrentTripStartPoint() == null) {
				setCurrentTripByEnterOut(busInstance);
				busInstance.setCurrentTripStartPoint(busInstance);
			}else{
				// 趟次没有结束,取上一个点的趟次信息
				setCurrentTripByPrePoint(busInstance);
			}
		} else {
			// 趟次没有结束,取上一个点的趟次信息
			setCurrentTripByPrePoint(busInstance);
		}
	}
	
	private void setCurrentTripByTripOver(BusInstance busInstance){
		if(busInstance.isInStandBy()){
			// 在待发区
			setCurrentTripByStandby(busInstance);
			
		}else if(busInstance.isEnterOut()){
			setCurrentTripByEnterOut(busInstance);
		}
	}
	
	private void setCurrentTripByStandby(BusInstance busInstance){
		DeparterSchedule ds = scheduleService.getDeparterScheduleNearestNotStart(busInstance.getLineUuid(), busInstance.getLineType(), busInstance.getBusUuid(), busInstance.getTime());
		if(ds != null){
			// 班次
			busInstance.setCurrentShift(PMSUtils.isNull(ds.getBrsdShift()));
			busInstance.setCurrentTrip(PMSUtils.isNull(ds.getBrsdTrip()));
			busInstance.setCurrentTripPlanTime(ds.getBrsdDepartureTime());
//			busInstance.setCurrentTripStartTime(DateUtils.formatDateTimeMinute(busInstance.getCurrentTime()));
		}
	}

	private void setCurrentTripByEnterOut(BusInstance busInstance){
		DeparterSchedule ds = scheduleService.getDeparterScheduleNearestNotStart(busInstance.getLineUuid(), busInstance.getLineType(), busInstance.getBusUuid(), busInstance.getTime());
		
		if(ds != null){
			// 班次
			busInstance.setCurrentShift(PMSUtils.isNull(ds.getBrsdShift()));
			busInstance.setCurrentTrip(PMSUtils.isNull(ds.getBrsdTrip()));
			busInstance.setCurrentTripPlanTime(ds.getBrsdDepartureTime());
		}
		busInstance.setCurrentTripStartTime(DateUtils.formatDateTime(busInstance.getTime()));
	}
	
	private void setCurrentTripByPrePoint(BusInstance busInstance) {
		// 趟次没有结束,取上一个点的趟次信息
		TimingPoint point = busInstance.getTimingPoint(-1);
		busInstance.setCurrentShift(point.getCurrentShift());
		busInstance.setCurrentTrip(point.getCurrentTrip());
		busInstance.setCurrentTripPlanTime(point.getCurrentTripPlanTime());
		busInstance.setCurrentTripStartTime(point.getCurrentTripStartTime());
	}
	
	/**
	 * 计算上一趟次信息
	 */
	private void caculatePreTrip(BusInstance busInstance){
		MultiLog log = MultiLogUtil.getPositionJudgeLog(busInstance);
		
		TimingPoint prePoint = busInstance.getTimingPoint(-1);
		BusTrip busTrip = middlewareGpsCaculateService.getLastBusTrip(busInstance.getBusNumber(), prePoint.getTime());
		
		if(busTrip != null){
			// 更新数据库趟次信息
			scheduleService.updateBusSchedule(busTrip.getLineid(), busTrip.getLinetype(), busInstance.getBusUuid(), busTrip.getDoduuid(), busTrip.getStartTime(), busTrip.getEndTime());
			realTripCaculateHandler.realTripCaculate(busInstance, busTrip);
		}
	}


	/**
	 * 获取下一个发车时刻信息
	 * @param busInstance
	 */
	private void setNextDepartureSchedule(BusInstance busInstance){
		// 下一个趟次都是重新取，防止因为某个趟次时间过长导致下一趟次数据未刷新
		DeparterSchedule currentDs = scheduleService.getDeparterScheduleNearestNotStart(busInstance.getLineUuid(), busInstance.getLineType(), busInstance.getBusUuid(), busInstance.getTime());
		
		if(currentDs != null){
			DeparterSchedule nextDs = scheduleService.getDeparterScheduleNext(currentDs, null);
			long secondInterval = DateUtils.secondInterval(currentDs.getDepartureTime(), busInstance.getTime());
			
			if(nextDs != null
					&& secondInterval <= 60 *60
					){ // 如果时间差超过1个小时，忽略掉){
				busInstance.setNextShift(PMSUtils.isNull(nextDs.getBrsdShift()));
				busInstance.setNextTrip(PMSUtils.isNull(nextDs.getBrsdTrip()));
				busInstance.setNextTripPlanTime(DateUtils.formatDate(nextDs.getDepartureTime(), "HH:mm"));
			}else{
				busInstance.setNextShift("");
				busInstance.setNextTrip("");
				busInstance.setNextTripPlanTime("");
			}
		}
		
	}
}
